package com.client;

import org.apache.log4j.Logger;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;


/**
 * 微服务客户端
 */
@RefreshScope
@RestController
public class ComputeController {

    private final Logger logger = Logger.getLogger(getClass());

    @Autowired
    private DiscoveryClient client;

    /**
     * 定义了一套针对AMQP协议的基础操作
     */
    @Autowired
    private AmqpTemplate rabbitTemplate;

    @Value("${from}")
    private String from;

    /**
     * 为外部提供服务接口
     * @param a
     * @param b
     * @return
     */
    @RequestMapping(value = "/add" ,method = RequestMethod.GET)
    public Integer add(int a,int b) {
        ServiceInstance instance = client.getLocalServiceInstance();
        int r = a + b;

        //创建消息生产者 并发送到名为addResult的队列中
        this.rabbitTemplate.convertAndSend("addResult", r);

        logger.info(from+"/add, host:" + instance.getHost() + ", service_id:" + instance.getServiceId() + ", result:" + r);
        return r;
    }

}
